/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-08-18 14:11:33
 * @filename : static/nmm/src/views/joinus.js
 * @version : 
 * @description : 
 */
define(function(require, exports, module){

    var JoinusView, tempObj={}, mId='joinus', reRender=false,
    imglazyload = require('{component}imglazyload/zepto.imglazyload'),
    upload = require('{component}upload/upload'),
    tab = require('{component}tab/zepto.tabA');

    JoinusView = Backbone.View.extend({

        el: 'body',

        template: '',
        templateC: '',
        templateS: '',
        templateI: '',

        backStageCheck: true,

        initialize: function () {
            this.template   = require('{view}joinus.tpl');
            this.templateC  = require('{view}countryList.tpl');
            this.templateS  = require('{view}stateList.tpl');
            this.templateI  = require('{view}incomeList.tpl');
        },

        render: function (obj) {
            share.checkPermission();
            share.reRender(reRender,mId);
 
            if ($('#'+mId).length < 1) { 
                this.renderTpl();
                tab.opt.index = obj.num ? obj.num : 0;
                tab.init(); 
                this.bindEvt();
                this.initUpload();
                this.initCountryList();
                //this.initIncomeList();
            } else {
                $('#'+mId).css('display','block');
            }

            if (parseInt(obj.num) > 0) {
                tab.gotoTabs(obj.num);
                if (obj.num == 2) {
                    this.readyThreeData();
                } else if (obj.num ==1) {
                    this.readySecondData();
                }

            } else {
                tab.gotoTabs(0);
            }

        },

        renderTpl : function() {
            $('body').append(_.template(this.template, lang));
        },

        bindEvt : function() {
            var dom = $('#'+mId),tthis = this;
            
            dom.find('.register_option').on('change',function(){tthis.needBackStageCheck();});

            dom.find('.jbc-frist').on('tap',function(){tthis.handleFristData();});
            dom.find('.jbc-second').on('tap',function(){tthis.handleSecondData();});
            dom.find('.jbc-three').on('tap',function(){tthis.handleThreeData();});

            dom.find('.back').on('tap',function(){tthis.goBack();});
            dom.find('.gender_item').on('tap',function(){tthis.genderToggle(this);});
            dom.find('.jbb_top').on('tap',function(){tthis.goSignin();});
            dom.find('.jbb_bottom').find('span').first().on('tap',function(){tthis.goServiceText();});
            dom.find('.jbb_bottom').find('span').last().on('tap',function(){tthis.goPrivacyText();});
            dom.find('.fromAge').find('select').on('change',function(){
                var valF = $(this).find('option:selected').val(),
                    valT = dom.find('.toAge').find('select').find('option:selected').val();
                valT =valF > valT ? valF : valT; 
                tthis.toAgeSelect(valF,valT); 
            });
            dom.find('.toAge').find('select').on('change',function(){
                var valT = $(this).find('option:selected').val(),
                    valF = dom.find('.fromAge').find('select').find('option:selected').val() || valT;
                valF = valT > valF ? valF : valT;
                tthis.fromAgeSelect(valF,valT);
            });

            $("#country").live('change.joinus',function(){
                var val = $(this).find('option:selected').val();
                tthis.initStateList(val);
            });

            var inputF  = dom.find('#joinus_frist').find('input');
            inputF.keypress(function(e){
                 if (e.keyCode == 13) {
                     tthis.handleFristData(); 
                 } 
            });

            var inputS  = dom.find('#joinus_second').find('.r_zip').find('input');

            inputS.keypress(function(e){
                 if (e.keyCode == 13) {
                     tthis.handleSecondData(); 
                 } 
            });

            /*
            var inputT  = dom.find('#jbc_three').find('.jbc_input').find('input');
            inputT.keypress(function(e){
                 if (e.keyCode == 13) {
                     tthis.handleSecondData(); 
                 } 
            });
            */

        },
        fromAgeSelect : function(val,valT) {
            var html = '<select id="from_age" class="age_group">'+
                '<option value="" disabled selected></option>';
            for (var i = 18; i <= valT; i++) {
                if (i == val) {
                    html = html+'<option value='+i+' selected>'+i+'</option>';
                } else { 
                    html = html+'<option value='+i+'>'+i+'</option>';
                }
            }
            $('#joinus_three').find('.fromAge').html(html);
        },
        toAgeSelect : function(val,valT) {
            var html = '<select id="to_age" class="age_group">'+
                '<option value="" disabled selected></option>';
            for (var i = val; i<100; i++) { 
                if (i == valT) {
                    html = html+'<option value='+i+' selected>'+i+'</option>';
                } else { 
                    html = html+'<option value='+i+'>'+i+'</option>';
                }
            }
            $('#joinus_three').find('.toAge').html(html);
        },
        needBackStageCheck: function() {
            this.backStageCheck = true;
        },

        goServiceText : function() {
            window.location.href='#termsService/whole';
        },

        goPrivacyText : function() {
            window.location.href='#privacypolicy/whole'; 
        },

        goSignin : function() {
            window.location.href='#signin/whole'; 
        },

        goBack : function() {
            this.backStageCheck = false;
            if (tab.opt.index > 0) {
                window.location.href='#joinus/part/tab'+(tab.opt.index-1); 
            } else {
                window.location.href='#index/whole'; 
            }
             
            $('#'+mId).find('input').blur();
            $('#'+mId).find('select').blur();
        },

        genderToggle : function(tthis) {
            $(tthis).parent().find(".gender_item").each(function(){
                var type = $(this).attr('type');
                $(this).removeAttr('select').removeClass('gender_item_'+type+'_select').find('div').removeClass(type+'_select').addClass(type);      
            });
            var type = $(tthis).attr('type');

            $(tthis).attr('select',true).addClass('gender_item_'+type+'_select').find('div').removeClass(type).addClass(type+'_select');
        },

        handleFristData : function() {
            var bool = false, tthis = this, obj = {};
                obj.email = $("#joinus").find('input[name="email"]').val(),
                obj.username = $("#joinus").find('input[name="userName"]').val(),
                obj.password = $("#joinus").find('input[name="passWord"]').val();
                bool = this.regModelValidata(obj); // 前端验证

            if (bool) {
                if (this.backStageCheck) {
                    util.cloneObj(obj,tempObj);
                    this.ajaxFristData(obj);
                } else {
                    window.location.href='#joinus/part/tab1'; 
                }
            } else {
                share.error('console','invalid'); 
            }
        },

        ajaxFristData : function(data) {
            var dom = $('.jbc-frist');

            share.ajaxStartA(dom);
            var tthis = this,
            obj = {
                url : seajs.data.vars.apiUrl + 'check_user_account',
                type : 'POST',
                data : data,
                success : function(data) {
                    if (data.results == 1 ) {
                        tthis.backStageCheck = false;
                        window.location.href='#joinus/part/tab1'; 
                    } else {
                        tthis.backStageCheck = true;
                        $.each(data.data, function(k, v) {
                            var obj = { bool: false, msg: v.msg };
                            if (v.error_id == 1) {
                                obj.field = 'username';
                            }
                            if (v.error_id == 2) {
                                obj.field = 'email';
                            }
                            if (v.error_id == 3) {
                                obj.field = 'password';
                            }

                            tthis.renderError(obj);
                        });
                    }
                },
                error : function(xhr, errorType, error) {
                    share.error('alert','user_account http request failed!'); 
                },
                complete : function(xhr,status){
                    share.ajaxEndA(dom);
                } 
            };
            $.ajax(share.ajaxControl(obj));
        },

        readySecondData : function() {
             var match_gender = $('#joinus_second').find('.gender_item[select=true]').attr('val');
             if (match_gender == null || match_gender == '' ) {
                 this.genderToggle($('#joinus_second').find('.gender_item').eq(1));
             }
        },

        handleSecondData : function() {
            var bool = false, obj = {},
                date = new Date($("#joinus").find('input[name="age"]').val());
            obj.gender = $('#joinus_second').find('.gender_item[select=true]').attr('val');
            obj.age = share.ages($("#joinus").find('input[name="age"]').val());
            obj.age_year = date.getFullYear();
            obj.age_month = date.getMonth() + 1;
            obj.age_day = date.getDate();
            //obj.type = $("#income option:selected").val();
            obj.r_country = $("#country option:selected").val();
            obj.r_zip = $("#joinus").find('input[name="zipCode"]').val();

            if (obj.r_country && parseInt(obj.r_country) !== 0 && parseInt(obj.r_country) !== 31 && parseInt(obj.r_country) !== 180) {
                var state = $('#state option:selected').val();
                (state !== undefined) ? obj.r_state_id = state : ''; 
                obj.skip_zip_check = 1; 
            }

            bool = this.regModelValidata(obj); // 前端验证
            if (bool) {
                if (this.backStageCheck) {
                    util.cloneObj(obj,tempObj);
                    this.ajaxSecondData(obj);
                } else {
                    window.location.href='#joinus/part/tab2'; 
                }
            } else {
                share.error('console','invalid'); 
            }
        },

        ajaxSecondData : function(data) {
            var tthis = this;
            var dom = $('.jbc-second');
            share.ajaxStartA(dom);
            var obj = {
                url : seajs.data.vars.apiUrl + 'check_zip',
                type : 'POST',
                data : data,
                success : function(data) {
                    if (typeof(data.errcode) !== 'undefined') {
                        tthis.backStageCheck = true;
                        var obj = { bool: false, field: 'r_zip', msg: data.errmsg };
                        tthis.renderError(obj);
                    } else {
                        tthis.backStageCheck = false;
                        window.location.href='#joinus/part/tab2'; 
                    } 
                },
                error : function(xhr, errorType, error) {
                    share.error('alert','http request failed!'); 
                },
                complete : function(xhr,status){
                    share.ajaxEndA(dom);
                } 
            };
            if (parseInt(data.r_country) == 0 || parseInt(data.r_country) == 31 || parseInt(data.r_country) == 180) {
                $.ajax(share.ajaxControl(obj)); 
            } else {
                window.location.href='#joinus/part/tab2'; 
            };
        },

        readyThreeData : function() {
             var match_gender = $('#joinus_three').find('.gender_item[select=true]').attr('val');
             if (match_gender == null || match_gender == '' ) {
                 var num = 1, 
                     gender = parseInt($('#joinus_second').find('.gender_item[select=true]').attr('val'));
                 if (gender == 1) {
                     num = 0;
                 } else if (gender == 16) {
                     num = 2;
                 }
                 this.genderToggle($('#joinus_three').find('.gender_item').eq(num));
             }
        },

        handleThreeData : function() {
            var bool = false, obj = {};
            obj.match_gender = $('#joinus_three').find('.gender_item[select=true]').attr('val');
            obj.match_age_min = $("#joinus_three").find('#from_age option:selected').val();
            obj.match_age_max = $("#joinus_three").find('#to_age option:selected').val();
            bool = this.regModelValidata(obj);
            if (bool) {
                util.cloneObj(obj,tempObj);
                this.ajaxThreeData(tempObj);
            } 
        },

        ajaxThreeData : function(data) {
            var tthis = this,dom = $('.jbc-three');

            share.ajaxStartA(dom);
            var obj = {
                url : seajs.data.vars.apiUrl + 'register_with_img',
                type : 'POST',
                data : data,
                success : function(data) {
                    if (typeof (data.usr_id) !== 'undefined') {
                        share.setStorage("ms_user_info", JSON.stringify(data));
                        share.setStorage(data.usr_id, JSON.stringify(share.compatibleData(data))); 
                        util.setCookie('session_id', data.session_id, {path: '/'});
                        seajs.data.vars.apiAccessUrl =  domain+'/apis/' + data.session_id + '/';
                        window.location.href='#userList/whole';
                        share.delAllPage(); 
                    } else {
                        alert('Oops! Something\'s not right. Try again later.');
                    } 
                },
                error : function(xhr, errorType, error) {
                    share.error('alert','user_register http request failed!'); 
                },
                complete : function(xhr,status){
                    share.ajaxEndA(dom);
                } 
            };
            $.ajax(share.ajaxControl(obj)); 
        },

        tabErrorGoto : function(obj) {
            this.renderError(obj); 
            //$.fn.tab.gotoTabs(1);
        },

        initUpload : function() {
            upload.init({
                id : 'file',
                filter: 'image',
                maxsize: 2048000,
                url: seajs.data.vars.apiUrl + 'upload_tmp_picture',
                onSuccess: function(data) {
                    //$('#'+mId).find('.uploading').hide();
                    try {
                        var data = JSON.parse(data);
                        if (data.results == 1) {
                            $('#'+mId).find('.uploading').hide();
                            //tempObj.img = data.url;
                            //$('#img_show').html('<img class="imglazyload" src = "" url="'+data.url+'"/>');
                            //$('#'+mId).imglazyload({startY : 0,endY: $(window).height(),sW:100,sH:100}); 
                        }
                    } catch(err){};
                },
                onError: function(data){console.log(data)},
                onProgress: function(evt){},
                onReader: function(evt) {
                    var img = evt.target.result;
                    $('#img_show').html('<img class="imglazyload" src = "" url="'+img+'"/>');  
                    $('#'+mId).imglazyload({startY : 0,endY: $(window).height(),sW:100,sH:100}); 
                    $('#'+mId).find('.uploading').show();
                } 
            });
        },
        initIncomeList : function() {
            share.getIncomeList({ callback: function(data, obj) {
                $('.type').html(_.template(obj.parentObj.templateI, { arr: data.data }));
            }, parentObj: this});
        },

        initCountryList : function() {
            share.getCountryList({ callback: function(data, obj) {
                $('.r_country').html(_.template(obj.parentObj.templateC, { arr: data.data }));
            }, parentObj:this });
        },

        initStateList : function(val) {
            var tthis = this,val = parseInt(val);
            if (val !== 0 && val !== 31 && val !== 180) {
                share.getStateList({ callback: function(data, obj) {
                    if (data.data.length > 0 ) {
                        $('.r_state').html(_.template(obj.parentObj.templateS, { arr: data.data }));
                    } else {
                        tthis.clearState();                       
                    }
                }, parentObj: this, country: val });
            } else {
                tthis.clearState();                       
            };
        },

        clearState : function() {
            var stateobj = $('#'+mId).find('.r_state');
            if (stateobj !== undefined) {
                stateobj.html('');
                if (stateobj.next().hasClass('err')) {
                    stateobj.next().remove();
                }
             }
        },

        renderError : function(obj) {
            var dom =  $('#'+mId).find('.'+obj.field+'');
            if (obj.field =='gender' || obj.field == 'lookForGender') {
                if (dom.next().hasClass('err')) {
                    dom.next().remove();
                }
                if (!obj.bool) {
                    dom.after("<div class='err'>"+obj.msg+"</div>");
                }
            } else {
                if (dom.next().hasClass('err')) {
                    dom.next().remove();
                    dom.find('input').removeAttr('style').removeClass('input_err');
                    dom.find('select').removeAttr('style').removeClass('input_err');
                }
                if (!obj.bool) {
                    dom.after("<div class='err'>"+obj.msg+"</div>");
                    dom.find('input').css('borderColor','#f00').addClass('input_err');
                    dom.find('select').css('borderColor','#f00').addClass('input_err');
                }
            }
        },

        regModelValidata : function(model) {
            var tthis=this,bool = true;
            for (var x in model) {
                (function(x,model){
                var obj = tthis.regFieldValidata(x,model);
                    tthis.renderError(obj);
                    if (!obj.bool) {
                        bool = false;
                    } 
                })(x,model);
            }
            return bool;
        },

        regFieldValidata : function(field,model) {
            var obj = {bool : true, field:field};
            var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._])+$/; 
            switch(field) {
                case 'email' :
                    if (model[field] == null || $.trim(model[field]) == '') { 
                        obj.bool = false;
                        obj.msg = lang.required;
                    } else if (!util.isEmail(model[field])) {
                        obj.bool = false;
                        obj.msg = lang.email_format_error;
                    }
                    break;

                case 'username': 
                    var arr = model['email'].split('@');
                    if (model[field] == null || $.trim(model[field]) == '') {
                        obj.bool = false;
                        obj.msg = lang.required;
                    } else if (!patrn.exec(model[field])) {
                        obj.bool = false;
                        obj.msg = lang.username_format_error;
                    } else if (!util.isLength(model[field],6,18)) {
                        obj.bool = false;
                        obj.msg = lang.username_length_error;
                    } else if (arr[0].toLowerCase() == model[field].toLowerCase()) {
                        obj.bool = false;
                        obj.msg = lang.joinus_username_error;
                    }
                    break;

                case 'password':
                    if (model[field] == null || $.trim(model[field]) == '') {
                        obj.bool = false;
                        obj.msg = lang.required;
                    } else if (!util.isLength(model[field],6,18)) {
                        obj.bool = false;
                        obj.msg = lang.password_format_error;
                    }
                    break;

                case 'match_gender':
                case 'gender':
                    if (model[field] == null || model[field] == '') {
                        obj.bool = false;
                        obj.msg = lang.joinus_gender;
                    }
                    break;
                case 'age':
                    if (model[field] == null || model[field] === '') {
                        obj.bool = false;
                        obj.msg = lang.required;
                    } else if (model[field] > 99) {
                        obj.bool = false;
                        obj.msg = lang.joinus_age_99;
                    } else if (model[field] < 18) {
                        obj.bool = false;
                        obj.msg = lang.joinus_age_18;
                    }
                    break;
                case 'type':
                case 'r_country':
                case 'r_state':
                    if (model[field] == null || model[field] == '') {
                        obj.bool = false;
                        obj.msg = lang.required;
                    }
                    break;
                case 'r_zip':
                    if (typeof(model['skip_zip_check']) !== 'undefined') {
                        break;
                    }
                    if (model[field] == null || model[field] == '') {
                        obj.bool = false;
                        obj.msg = lang.required;
                    }
                    break;
                case 'img':
                    break;

                case 'match_age_min' :
                case 'match_age_max' :
                    if (model[field] == null || model[field] == '') {
                        obj.bool = false;
                        obj.msg = lang.required;
                    } 
                    if (field == 'match_age_max') {
                        if (model[field]<model['match_age_min']) {
                            obj.bool = false;
                            obj.msg = lang.joinus_lookfor_age;
                        }
                    }
                    break;
            }

            return obj;
        },
    });
    module.exports = JoinusView;
})

